package com.example.project.controller;

import com.example.project.dto.FileDTO;
import com.example.project.entity.File;
import com.example.project.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * (File)表控制层
 *
 * @author makejava
 * @since 2024-02-23 15:18:23
 */
@CrossOrigin
@RestController
@RequestMapping("file")
public class FileController {
    /**
     * 服务对象
     */

    @Resource
    private FileService fileService;
    // 文件保存的根路径
    @Value("${basepath}")
    private String basePath;

    /**
     * 分页查询
     *
     * param file 筛选条件
     * param pageRequest      分页对象
     * @return 查询结果
     */
    @PostMapping("findPage")
    public ResponseEntity<Page<File>> queryByPage(@RequestBody FileDTO data) {
        com.example.project.entity.Page page = data.getPage();
        return ResponseEntity.ok(this.fileService.queryByPage(data.getFile(), PageRequest.of(page.getPage(),page.getSize())));
    }
    /**
     * 条件查询
     * @param data 筛选条件
     * @return 查询结果
     * */
    @PostMapping("find")
    public ResponseEntity<List<File>> queryBy(@RequestBody File data) {
        return ResponseEntity.ok(this.fileService.queryBy(data));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */

    @PostMapping("{id}")
    public ResponseEntity<File> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.fileService.queryById(id));
    }
    /**
     * 文件下载
     *  @param file 实体
     * */
    @PutMapping("download")
    public ResponseEntity<byte[]> download(@RequestBody File file) throws IOException {
        return ResponseEntity.ok(this.fileService.download(file).getBody());
    }
    /**
     * 新增数据
     *
     * @param file 实体
     * @return 新增结果
     */
    @PostMapping("add")
    public File insert(@RequestBody MultipartFile file ) {

        // 原始文件名
        String fileName = file.getOriginalFilename();
        // 后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = fileName + tempName.toString();
        Path path = Paths.get(basePath + newFileName);


        // 往数据库中插件记录
        File fileAttach = new File();
        fileAttach.setFilePath(path.toString());
        fileAttach.setFileSize(Double.valueOf(file.getSize()));
        fileAttach.setFileName(fileName);
        fileAttach.setNewName(newFileName);
        fileAttach.setFileCreateTime(LocalDateTime.now());
        fileAttach.setFlieType(suffixName);
        try {
            //保存文件
            byte[] bytes = file.getBytes();
            // 往本地磁盘保存文件
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return this.fileService.insert(fileAttach);
    }
    /**
     * 编辑数据
     * 只能绑定一个
     * @param file 实体
     * @return 编辑结果
     */
    @PutMapping("put1")
    public ResponseEntity<File> edit(@RequestBody File file) {
        return ResponseEntity.ok(this.fileService.update1(file));
    }
    /**
     * 编辑数据
     *
     * @param file 实体
     * @return 编辑结果
     */
    @PutMapping("put")
    public ResponseEntity<File> edit1(@RequestBody File file) {
        return ResponseEntity.ok(this.fileService.update(file));
    }

    /**
     * 文件绑定
     *  @param file 实体
     * */
    @PutMapping("binding")
    public ResponseEntity<File> binding (@RequestBody File file){
        return ResponseEntity.ok(this.fileService.update(file));
    }


    /**
     * 删除数据
     *
     * param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("del")
    public ResponseEntity<Boolean> deleteById(@RequestBody File data) {

        return ResponseEntity.ok(this.fileService.deleteById(data.getFileId()));
    }

}

